import { useState, useEffect } from "react";
import { zodResolver } from "@hookform/resolvers/zod";
import { useForm } from "react-hook-form";
import * as z from "zod";
import {
  Form,
  FormControl,
  FormDescription,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from "@/components/ui/form";
import { Input } from "@/components/ui/input";

import { useToast } from "./hooks/use-toast";

const formSchema = z.object({
  originalUrl: z.string().url({
    message: "请输入一个有效的URL",
  }),
  customCode: z.string().optional(),
  duration: z.string().optional(),
});

export default function App() {
  const { toast } = useToast();
  const [shortUrl, setShortUrl] = useState<string>("");
  const [isSubmitting, setIsSubmitting] = useState<boolean>(false);
  const [showResults, setShowResults] = useState<boolean>(false);

  const form = useForm<z.infer<typeof formSchema>>({
    resolver: zodResolver(formSchema),
    defaultValues: {
      originalUrl: "",
      customCode: "",
    },
  });

  useEffect(() => {
    if (shortUrl) {
      setTimeout(() => {
        setShowResults(true);
      }, 300);
    } else {
      setShowResults(false);
    }
  }, [shortUrl]);

  async function onSubmit(values: z.infer<typeof formSchema>) {
    try {
      setIsSubmitting(true);
      const response = await fetch("/api/url/add", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({
          original_url: values.originalUrl,
          custom_code: values.customCode || undefined,
          duration: values.duration ? Number(values.duration) : undefined,
        }),
      });

      if (!response.ok) {
        throw new Error("创建失败");
      }

      const data = await response.json();
      setShortUrl(data.short_url);
      toast({
        title: "创建成功",
        description: "短链接生成完成",
      });
    } catch (error) {
      toast({
        title: "出现错误",
        description: "服务器可能已经挂了，请重试" + error,
        variant: "destructive",
      });
    } finally {
      setIsSubmitting(false);
    }
  }

  function copyToClipboard(text: string) {
    if (navigator.clipboard && navigator.clipboard.writeText) {
      navigator.clipboard
        .writeText(text)
        .then(() => {
          toast({
            title: "复制成功",
            description: "链接已复制到剪贴板",
          });
        })
        .catch((err) => console.error("Failed to copy text: ", err));
    } else {
      const textarea = document.createElement("textarea");
      textarea.value = text;
      textarea.style.position = "fixed";
      textarea.style.top = "-1000px";
      document.body.appendChild(textarea);
      textarea.focus();
      textarea.select();

      try {
        const successful = document.execCommand("copy");
        if (successful) {
          toast({
            title: "复制成功",
            description: "链接已复制到剪贴板",
          });
        } else {
          console.error("Failed to copy text");
        }
      } catch (err) {
        console.error("Fallback: Unable to copy text", err);
      }

      document.body.removeChild(textarea);
    }
  }

  return (
    <div className="min-h-screen flex flex-col items-center justify-center px-4 py-12 bg-[#f5f5f7] overflow-hidden relative">
      {/* 苹果风格背景装饰 */}
      <div className="absolute top-0 left-0 right-0 overflow-hidden z-0 h-[20vh] pointer-events-none">
        <div className="absolute top-[-350px] left-[10%] w-[600px] h-[600px] rounded-full bg-gradient-to-br from-[#42a4ff]/20 to-[#0066cc]/5 blur-[80px] opacity-70"></div>
        <div className="absolute top-[-400px] right-[5%] w-[500px] h-[500px] rounded-full bg-gradient-to-br from-[#3bf0e4]/10 to-[#bca1f7]/5 blur-[60px] opacity-60"></div>
      </div>
      <div className="absolute bottom-0 left-0 right-0 overflow-hidden z-0 h-[30vh] pointer-events-none">
        <div className="absolute bottom-[-200px] right-[15%] w-[400px] h-[400px] rounded-full bg-gradient-to-tr from-[#ff9e7f]/10 to-[#ffbf7f]/5 blur-[60px] opacity-50"></div>
      </div>

      <div className="w-full max-w-md mx-auto relative z-10">
        <div className="absolute inset-0 bg-white/20 rounded-[32px] backdrop-blur-xl shadow-[0_20px_80px_-10px_rgba(0,0,0,0.1)] transform translate-y-2 scale-[0.98] z-0 apple-transition"></div>

        <div className="apple-glassmorphism apple-card-hover rounded-[28px] p-8 relative z-10 apple-transition">
          <div className="flex items-center justify-center mb-8">
            <div className="w-16 h-16 flex items-center justify-center bg-gradient-to-tr from-[#147ce5] to-[#2bc4df] rounded-[22px] shadow-[0_8px_16px_rgba(20,124,229,0.25)] mb-4 transform rotate-12 apple-pulse apple-float">
              <svg
                xmlns="http://www.w3.org/2000/svg"
                width="28"
                height="28"
                viewBox="0 0 24 24"
                fill="none"
                stroke="white"
                strokeWidth="2.5"
                strokeLinecap="round"
                strokeLinejoin="round"
                className="transform -rotate-12"
              >
                <path d="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"></path>
                <path d="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"></path>
              </svg>
            </div>
          </div>

          <h1 className="text-[28px] font-semibold text-center mb-1 text-[#1d1d1f] apple-gradient-text">
            短链接生成器
          </h1>
          <p className="text-center text-[#86868b] mb-8">
            简洁、易用、可定制的链接缩短工具
          </p>

          <Form {...form}>
            <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-6">
              <FormField
                control={form.control}
                name="originalUrl"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel className="text-[#1d1d1f] font-medium text-sm">
                      原始链接
                    </FormLabel>
                    <FormControl>
                      <div className="relative">
                        <Input
                          placeholder="https://example.com"
                          {...field}
                          className="rounded-xl border-[#d2d2d7] focus:border-[#0071e3] focus:ring-[#0071e3] h-12 bg-white/70 pl-10 apple-input-focus transition-all duration-300"
                        />
                        <div className="absolute left-3 top-1/2 transform -translate-y-1/2 text-[#86868b]">
                          <svg
                            xmlns="http://www.w3.org/2000/svg"
                            width="18"
                            height="18"
                            viewBox="0 0 24 24"
                            fill="none"
                            stroke="currentColor"
                            strokeWidth="2"
                            strokeLinecap="round"
                            strokeLinejoin="round"
                          >
                            <path d="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"></path>
                            <path d="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"></path>
                          </svg>
                        </div>
                      </div>
                    </FormControl>
                    <FormMessage className="text-[#bf4800] text-xs mt-1" />
                  </FormItem>
                )}
              />

              <div className="grid grid-cols-3 gap-4">
                <FormField
                  control={form.control}
                  name="customCode"
                  render={({ field }) => (
                    <FormItem className="col-span-2">
                      <FormLabel className="text-[#1d1d1f] font-medium text-sm">
                        自定义别名
                      </FormLabel>
                      <FormControl>
                        <div className="relative">
                          <Input
                            placeholder="custom-code"
                            {...field}
                            className="rounded-xl border-[#d2d2d7] focus:border-[#0071e3] focus:ring-[#0071e3] h-12 bg-white/70 pl-10 apple-input-focus transition-all duration-300"
                          />
                        </div>
                      </FormControl>
                      <FormDescription className="text-[#86868b] text-xs mt-1">
                        4-10个字符（可选）
                      </FormDescription>
                      <FormMessage className="text-[#bf4800] text-xs" />
                    </FormItem>
                  )}
                />

                <FormField
                  control={form.control}
                  name="duration"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel className="text-[#1d1d1f] font-medium text-sm">
                        有效期
                      </FormLabel>
                      <FormControl>
                        <div className="relative">
                          <Input
                            placeholder="10"
                            type="number"
                            {...field}
                            className="rounded-xl border-[#d2d2d7] focus:border-[#0071e3] focus:ring-[#0071e3] h-12 bg-white/70 pl-10 apple-input-focus transition-all duration-300"
                          />
                          <div className="absolute left-3 top-1/2 transform -translate-y-1/2 text-[#86868b]">
                            <svg
                              xmlns="http://www.w3.org/2000/svg"
                              width="18"
                              height="18"
                              viewBox="0 0 24 24"
                              fill="none"
                              stroke="currentColor"
                              strokeWidth="2"
                              strokeLinecap="round"
                              strokeLinejoin="round"
                            >
                              <circle cx="12" cy="12" r="10"></circle>
                              <polyline points="12 6 12 12 16 14"></polyline>
                            </svg>
                          </div>
                        </div>
                      </FormControl>
                      <FormDescription className="text-[#86868b] text-xs mt-1">
                        天数（可选）
                      </FormDescription>
                      <FormMessage className="text-[#bf4800] text-xs" />
                    </FormItem>
                  )}
                />
              </div>

              <button
                type="submit"
                disabled={isSubmitting}
                className={`w-full h-12 relative bg-[#0071e3] text-white font-medium rounded-full hover:bg-[#0077ed] active:scale-[0.98] transition-all duration-300 ease-in-out shadow-sm overflow-hidden apple-button-hover ${
                  isSubmitting ? "opacity-70" : ""
                }`}
              >
                <span
                  className={`absolute inset-0 flex items-center justify-center transition-all duration-300 ${
                    isSubmitting ? "opacity-0" : "opacity-100"
                  }`}
                >
                  生成短链接
                </span>
                <span
                  className={`absolute inset-0 flex items-center justify-center transition-all duration-300 ${
                    isSubmitting ? "opacity-100" : "opacity-0"
                  }`}
                >
                  <svg
                    className="animate-spin h-5 w-5 text-white"
                    xmlns="http://www.w3.org/2000/svg"
                    fill="none"
                    viewBox="0 0 24 24"
                  >
                    <circle
                      className="opacity-25"
                      cx="12"
                      cy="12"
                      r="10"
                      stroke="currentColor"
                      strokeWidth="4"
                    ></circle>
                    <path
                      className="opacity-75"
                      fill="currentColor"
                      d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"
                    ></path>
                  </svg>
                </span>
              </button>
            </form>
          </Form>
        </div>

        {shortUrl && (
          <div
            className={`mt-6 apple-glassmorphism rounded-[28px] p-6 text-center apple-transition transform relative z-10 ${
              showResults
                ? "opacity-100 translate-y-0"
                : "opacity-0 translate-y-4"
            }`}
          >
            <p className="text-[#1d1d1f] font-medium mb-4">生成的短链接</p>
            <div className="flex items-center justify-center mb-3">
              <div className="bg-[#f2f7fd] rounded-lg p-3 max-w-full overflow-hidden apple-shadow-sm">
                <div className="flex items-center">
                  <a
                    href={shortUrl}
                    className="text-[#0071e3] hover:underline truncate max-w-[240px] text-base font-medium"
                    target="_blank"
                    rel="noopener noreferrer"
                  >
                    {shortUrl}
                  </a>
                  <button
                    onClick={() => copyToClipboard(shortUrl)}
                    className="ml-3 inline-flex items-center justify-center w-8 h-8 rounded-full bg-white hover:bg-[#0071e3] hover:text-white text-[#0071e3] transition-colors duration-200 shadow-sm apple-button-hover"
                    aria-label="复制链接"
                  >
                    <svg
                      xmlns="http://www.w3.org/2000/svg"
                      width="16"
                      height="16"
                      viewBox="0 0 24 24"
                      fill="none"
                      stroke="currentColor"
                      strokeWidth="2"
                      strokeLinecap="round"
                      strokeLinejoin="round"
                    >
                      <rect
                        x="9"
                        y="9"
                        width="13"
                        height="13"
                        rx="2"
                        ry="2"
                      ></rect>
                      <path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"></path>
                    </svg>
                  </button>
                </div>
              </div>
            </div>
            <div className="flex items-center justify-center space-x-1">
              <p className="text-xs text-[#86868b]">点击链接访问</p>
              <span className="text-xs text-[#86868b]">•</span>
              <p className="text-xs text-[#86868b]">点击按钮复制</p>
            </div>
          </div>
        )}
      </div>

      <div className="mt-12 text-xs text-[#86868b] text-center apple-transition relative z-10">
        <div className="mb-2">
          <span className="inline-block w-6 h-6 mx-1 rounded-full bg-gradient-to-r from-[#0066cc] to-[#42a4ff] apple-shadow-sm"></span>
          <span className="inline-block w-3 h-3 mx-1 rounded-full bg-[#86868b] opacity-30"></span>
          <span className="inline-block w-3 h-3 mx-1 rounded-full bg-[#86868b] opacity-30"></span>
        </div>
        <p>© {new Date().getFullYear()} 短链接生成器 • 简单易用</p>
      </div>
    </div>
  );
}
